#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<string.h>
#include<sys/wait.h>

int main(){

	int fd = open("data.txt", O_RDWR);
	char buf[1024];
	if (-1 == fd) {
		perror("open error");
		return -1;
	}
	bzero(buf, 0);
	int ret;
	
	pid_t pid = fork();
	if (pid == 0) {
		strcpy(buf, "HelloWorld");
		ret = write(fd, buf, strlen(buf));
		if (-1 == ret) {
			perror("write error");
			close(fd);
			return 0;
		}
		sleep(1);

		bzero(buf, 0);
		ret = read(fd, buf, 1024);
		if (-1 == ret) {
			perror("read error");
			close(fd);
			return 0;
		}
		printf("child read data: %s\n", buf);
		close(fd);
	} else if (pid > 0){
		sleep(1);
		ret = read(fd, buf, 1024);
		if (-1 == ret) {
			perror("read error");
			close(fd);
			return 0;
		}
		printf("parent read data: %s\n", buf);

		ret = write(fd, "XXXXXXXXXX", 11);
		if (-1 == ret) {
			perror("write error");
			close(fd);
			return 0;
		}

		close(fd);
		wait(0);
	} else {
		perror("fork error");
	}

	return 0;
}
